package com.hqyj.freemovie.front.test;

public class TicketDemoWithRunnable implements Runnable {

    private final SaleWindow saleWindow;

    public TicketDemoWithRunnable(SaleWindow saleWindow){
        this.saleWindow = saleWindow;
    }

    @Override
    public void run() {
        while (true){
            synchronized (saleWindow){
                if(Ticket.TICKET_NUM<=0){
                    System.out.println("今天的门票全部售完！！");
                    break;
                }

                Ticket.TICKET_NUM--;
                if( "窗口A".equals(Thread.currentThread().getName())){
                    System.out.println("A窗口售出一张票，还剩：" + Ticket.TICKET_NUM+"张门票...");
                    saleWindow.windowsASaleNumber++;
                }
                if( "窗口B".equals(Thread.currentThread().getName())){
                    System.out.println("B窗口售出一张票，还剩：" + Ticket.TICKET_NUM+"张门票...");
                    saleWindow.windowsBSaleNumber++;
                }
                if( "窗口C".equals(Thread.currentThread().getName())){
                    System.out.println("C窗口售出一张票，还剩：" + Ticket.TICKET_NUM+"张门票...");
                    saleWindow.windowsCSaleNumber++;
                }
            }
        }
    }


    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        SaleWindow saleWindow = new SaleWindow(ticket);
        TicketDemoWithRunnable ticketDemoWithRunnable = new TicketDemoWithRunnable(saleWindow);
        Thread windowAThread = new Thread(ticketDemoWithRunnable,"窗口A");
        Thread windowBThread = new Thread(ticketDemoWithRunnable,"窗口B");
        Thread windowCThread = new Thread(ticketDemoWithRunnable,"窗口C");

        windowAThread.start();
        windowBThread.start();
        windowCThread.start();

        try{
            windowAThread.join();
            windowBThread.join();
            windowCThread.join();
        }catch (Exception ex){
            ex.printStackTrace();
        }
        System.out.println("A窗口卖了："+saleWindow.windowsASaleNumber+"张票");
        System.out.println("B窗口卖了："+saleWindow.windowsBSaleNumber+"张票");
        System.out.println("C窗口卖了："+saleWindow.windowsCSaleNumber+"张票");
    }
}
